import * as Api from '../apis/secondaryVerify';
import {
    observable,
    action,
} from 'mobx';
import {
    WeaForm,
} from 'comsMobx';
import {
    WeaMoreButton,
    WeaLocaleProvider,
} from 'ecCom';
import {
    message,
    Button,
} from 'antd';
import {
    fetch
} from '../util/py-util';
import {
    RSAEcrypt
} from '../util/RSAUtil'
const getLabel = WeaLocaleProvider.getLabel;

export class HrmSecondaryVerify {
    //*************************RSA********************************
    //是否开启了RSA加密
    @observable openRSA = "0";
    //*************************SecondaryVerify********************************
    @observable date = new Date().getTime();

    @action setDate = () => {
        this.date = new Date().getTime();
    }

    @observable secondaryVerify = {
        isSetted: false,
        loading: true,
    }

    isSettedSecondaryPwd = () => {
        fetch({
            Api,
            name: 'isSettedSecondaryPwd',
            logic: (cb) => {
                const {
                    isSetted
                } = cb;

                this.secondaryVerify.loading = false;
                this.secondaryVerify.isSetted = isSetted;
                if (isSetted) {
                    this.mainDialog.isPassLoginPassword = true;
                }
            }
        });
    }

    setSecondaryVerify = () => {
        this.openDialog({
            type: 'set'
        });
    }

    modifySecondaryPass = () => {
        this.openDialog({
            type: 'modify'
        });
    }


    //*************************MainDialog********************************
    @observable mainDialog = {
        visible: false,
        title: '',
        isPassLoginPassword: false,
    }

    getButtonName = () => {
        const {
            isPassLoginPassword
        } = this.mainDialog;

        let name;
        if (!isPassLoginPassword) {
            name = getLabel('504372', "下一步");
        } else {
            name = getLabel('504373', '保存');
        }

        return name;
    }

    getBtnCallback = () => {
        const {
            isPassLoginPassword
        } = this.mainDialog;

        if (!isPassLoginPassword) {
            this.checkPassword()
        } else {
            this.saveSecondaryPassword();
        }
    }

    checkPassword = () => {
        const {
            form
        } = this.formInfo;
        let RSAParam = {
            password: form.getFormParams().password
        }
        RSAEcrypt(this.openRSA, RSAParam).then(RSAParam => {
            form.validateForm().then(f => {
                if (f.isValid) {
                    fetch({
                        Api,
                        name: 'checkPassword',
                        fetchParams: {
                            ...form.getFormParams(),
                            password: RSAParam.password
                        },
                        logic: (cb) => {
                            const {
                                result
                            } = cb;

                            this.mainDialog.isPassLoginPassword = result;

                            if (result) {
                                this.setDialogTitle({
                                    type: 'modify'
                                });
                                this.resetFormInfo();
                                this.getFormConditions();
                            } else {
                                form.showError('password', getLabel('504343', "登录密码错误"));
                            }
                        }
                    });
                } else {
                    f.showErrors();
                }
            });
        });

    }

    saveSecondaryPassword = () => {
        const {
            form,
            passwordComplexity,
            minpasslen,
            isOldPwdPass,
            isEqualToLoginPass,
        } = this.formInfo, {
            secondaryPwd1,
            newSecondaryPwd1,
            secondaryPwd2,
            newSecondaryPwd2,
        } = form.getFormParams();

        const pwd1 = secondaryPwd1 || newSecondaryPwd1,
            pwd2 = secondaryPwd2 || newSecondaryPwd2;

        const key = secondaryPwd1 ? 'secondaryPwd1' : 'newSecondaryPwd1';
        form.validateForm().then(f => {
            if (f.isValid) {
                if (newSecondaryPwd1 && !isOldPwdPass) {
                    form.showError('oldSecondaryPwd', getLabel('504374', "旧密码校验不通过！"));
                    return;
                }

                if (isEqualToLoginPass) {
                    form.showError(key, getLabel('504375', "二次验证密码不能和登录密码相同"));
                    return;
                }

                if (!this.isEqual(pwd1, pwd2)) {
                    form.showError(secondaryPwd2 ? 'secondaryPwd2' : 'newSecondaryPwd2', getLabel('504376', "密码确认不正确！"));
                    return;
                }

                if (['1','2','3'].includes(passwordComplexity) && !this.isPassRegExp(pwd1, passwordComplexity)) {
                    let msg;
                    if (passwordComplexity == '1') {
                        msg = getLabel('512768',"新密码不符合要求，必须包含字母大写、字母小写、数字！请重新输入！");
                    }
                    if (passwordComplexity == '2') {
                        msg = getLabel('512769',"新密码不符合要求，必须包含字母、数字、特殊字符！请重新输入！");
                    }
                    if (passwordComplexity == '3') {
                        msg = getLabel('512767', "新密码不符合要求，必须包含字母、数字！请重新输入！");
                    }
                    form.showError(key, msg);
                    return;
                }

                if (!this.isReachMinLen(pwd1, minpasslen)) {
                    form.showError(key, `${getLabel('504379', "密码长度不能小于")}${minpasslen}`);
                    return;
                }
                let RSAParam = {};
                if (key === 'secondaryPwd1') {
                    RSAParam = {
                        secondaryPwd1:form.getFormParams().secondaryPwd1,
                        secondaryPwd2:form.getFormParams().secondaryPwd2
                    }
                } else {
                    RSAParam = {
                        oldSecondaryPwd:form.getFormParams().oldSecondaryPwd,
                        newSecondaryPwd1:form.getFormParams().newSecondaryPwd1,
                        newSecondaryPwd2:form.getFormParams().newSecondaryPwd2
                    }
                }
                RSAEcrypt(this.openRSA,RSAParam).then(RSAParam=>{
                    fetch({
                        Api,
                        name: 'saveSecondaryPwd',
                        fetchParams: {
                            ...form.getFormParams(),
                            ...RSAParam
                        },
                        logic: (cb) => {
                            const {
                                sign
                            } = cb;

                            if (sign == '1') {
                                message.success(cb.message);
                                this.secondaryVerify.isSetted = true;
                                this.closeDialog();
                            } else {
                                message.warning(cb.message);
                                this.setDate();
                            }
                        }
                    });
                });
            } else {
                f.showErrors();
            }
        });
    }

    isEqual = (secondaryPwd1, secondaryPwd2) => {
        if (secondaryPwd1 !== secondaryPwd2) {
            return false;
        }
        return true;
    }

    isPassRegExp = (secondaryPwd1, passwordComplexity) => {
        let regExp;
        let isPassRegExp = true;
        if (passwordComplexity == '1') {
            regExp = [/[a-z]+/, /[A-Z]+/, /\d+/];
        } else if (passwordComplexity == '2') { 
            regExp = [/[a-zA-Z_]+/, /\W+/, /\d+/];
        } else if (passwordComplexity == '3') { 
            regExp = [/[a-zA-Z_]+/, /\d+/];
        }
        regExp.map(reg => {
            if (!reg.test(secondaryPwd1)) {
                isPassRegExp = false;
            }
        });

        return isPassRegExp;

    }

    isReachMinLen = (secondaryPwd1, minpasslen) => {
        if (secondaryPwd1.length < minpasslen) {
            return false;
        }
        return true;
    }

    get buttons() {
        const {
            loading
        } = this.formInfo;

        const buttons = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rkwxrl@1`} type="primary" disabled={loading} onClick={() => this.getBtnCallback()}>{this.getButtonName()}</Button>),
            (<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@r9exog@2`} datas={this.dropMenuDatas} />)
        ]

        return buttons;
    }

    get style() {
        const style = {
            width: this.getWidth(),
            height: this.getHeight()
        }

        return style
    }

    getWidth = () => {
        const {
            isPassLoginPassword
        } = this.mainDialog;

        let width;
        if (!isPassLoginPassword) {
            width = 600;
        } else {
            width = 650;
        }

        return width
    }

    getHeight = () => {
        const {
            isPassLoginPassword
        } = this.mainDialog, {
            c_len
        } = this.formInfo;

        let height;
        if (!isPassLoginPassword) {
            height = 90;
        } else {
            height = c_len === 4 ? 250 : 210;
        }

        return height;

    }

    get dropMenuDatas() {
        const {
            isPassLoginPassword
        } = this.mainDialog, {
            loading
        } = this.formInfo;

        let dropMenuDatas = [];

        dropMenuDatas.push({
            key: '0',
            disabled: loading,
            icon: this.getDropMenuIcon(isPassLoginPassword),
            content: this.getDropMenuContent(isPassLoginPassword),
            disabled: loading,
            onClick: () => this.handleClick(isPassLoginPassword),
        })

        return dropMenuDatas;
    }

    getDropMenuIcon = (isPassLoginPassword) => {
        let icon;
        if (!isPassLoginPassword) {
            icon = <i className='icon-coms-Right' />;
        } else {
            icon = <i className='icon-coms-Preservation' />;
        }
        return icon;
    }

    getDropMenuContent = (isPassLoginPassword) => {
        let name;
        if (!isPassLoginPassword) {
            name = getLabel('504372', "下一步");
        } else {
            name = getLabel('504373', '保存');
        }
        return name;
    }

    handleClick = (isPassLoginPassword) => {
        if (!isPassLoginPassword) {
            this.checkPassword()
        } else {
            this.saveSecondaryPassword()
        }
    }

    @action
    openDialog = (params) => {
        this.setDialogTitle(params);
        this.mainDialog.visible = true;
    }

    @action
    setDialogTitle = (params) => {
        const {
            type
        } = params;
        if (type == 'set') {
            this.mainDialog.title = getLabel('504331', "请先输入登录密码")
        }
        if (type == 'modify') {
            this.mainDialog.title = getLabel('504332', "二次验证密码设置")
        }
    }

    @action
    closeDialog = () => {
        this.mainDialog.visible = false;
        if (!this.secondaryVerify.isSetted) {
            this.mainDialog.isPassLoginPassword = false;
        }
    }

    //*************************MainDialog********************************
    @observable formInfo = {
        conditions: [],
        form: new WeaForm(),
        loading: true,
        isOldPwdPass: false,
        isEqualToLoginPass: true,
        c_len: 1,
    }

    getFormConditions = () => {
        const {
            isPassLoginPassword
        } = this.mainDialog;

        fetch({
            Api,
            name: !isPassLoginPassword ? 'getPasswordForm' : 'getSecondaryPwdForm',
            logic: (cb) => {
                const {
                    conditions,
                    minpasslen,
                    openRSA
                } = cb;

                if (openRSA !== undefined) {
                    this.openRSA = openRSA;
                }

                if (minpasslen !== undefined) {
                    ['minpasslen', 'passwordComplexity', 'title'].map(v => {
                        this.formInfo[v] = cb[v]
                    });
                }

                this.handleConditions(conditions);
                this.formInfo.c_len = conditions[0].items.length;
                this.formInfo.conditions = conditions;
                this.formInfo.form.initFormFields(conditions);
                this.formInfo.loading = false;
            }
        });
    }

    handleConditions = (conditions) => {
        const {
            passwordComplexity,
            title
        } = this.formInfo;

        conditions.map(c => {
            c.items.map(item => {
                const key = item.domkey[0];
                if (key !== 'validatecode')
                    item.otherParams = {
                        type: 'password'
                    }
                if (['secondaryPwd1', 'newSecondaryPwd1'].includes(key)) {
                    item.otherParams = Object.assign(item.otherParams, {
                        tip: title,
                        passwordStrength: true,
                    });
                }
            });
        });
    }

    verifyPassword = (params) => {
        const {
            form
        } = this.formInfo, {
            cb,
            key
        } = params;
        let RSAParam = {
            password: cb
        }
        RSAEcrypt(this.openRSA,RSAParam).then(RSAParam =>{
            fetch({
                Api,
                name: (key == 'oldSecondaryPwd') ? 'checkOldSecondaryPwd' : 'checkNewSecondaryPwd',
                fetchParams: {
                    [key]: RSAParam.password
                },
                logic: (cb) => {
                    const {
                        result
                    } = cb;

                    if (key == 'oldSecondaryPwd') {
                        this.formInfo.isOldPwdPass = result;
                    } else {
                        this.formInfo.isEqualToLoginPass = !result;
                    }
                    const msg = (key == 'oldSecondaryPwd') ? getLabel('504374', "旧密码校验不通过！") : getLabel('504375', "二次验证密码不能和登录密码相同");
                    if (!result) {
                        form.showError(key, msg);
                    }
                }
            });
        });
    }

    resetFormInfo = () => {
        this.formInfo.conditions = [];
        this.formInfo.form = new WeaForm();
        this.formInfo.loading = true;
    }

    resetSecondaryVerify = () => {
        this.mainDialog.isPassLoginPassword = false;
    }
}